import React, { useEffect, useState } from 'react'
import { NavBar, Swiper, Tag, Modal, Dialog,Toast } from 'antd-mobile'
import { useLocation, useNavigate } from 'react-router-dom'
import { getHouseDetailAPI } from '../../apis/housedetail'
import { baseURL } from '../../utils/request'
import './index.scss'
import HousePackage from '../../components/housepackage'
import { getToken } from '../../utils/toke'
import { addFavoritesAPI, delFavoritesAPI, getFavoritesAPI } from '../../apis/profile'

// 百度地图
const BMap = window.BMapGL
const labelStyle = {
    position: 'absolute',
    zIndex: -7982820,
    backgroundColor: 'rgb(238, 93, 91)',
    color: 'rgb(255, 255, 255)',
    height: 25,
    padding: '5px 10px',
    lineHeight: '14px',
    borderRadius: 3,
    boxShadow: 'rgb(204, 204, 204) 2px 2px 2px',
    whiteSpace: 'nowrap',
    fontSize: 12,
    userSelect: 'none'
}
export default function HouseDetail() {
    const navigate = useNavigate()
    const location = useLocation()
    const [visible, setVisible] = useState(false)
    const [isFavorite, setIsFavorite] = useState(false)
    const [houseDetail, setHouseDetail] = useState({})
    async function getHouseDetail(id) {
        const res = await getHouseDetailAPI(id)
        console.log(res.body)
        setHouseDetail(res.body)
        renderMap(res.body.community, res.body.coord)
    }
    async function checkFavorite(id) {
        const isLogin = getToken()
        if (!isLogin) {
            return
        }
        // const id = location.pathname.split('/')[2]
        const res = await getFavoritesAPI(id)
        // console.log(res);
        const { status, body } = res
        if (status === 200) {
            // 表示请求已经成功，需要更新 isFavorite 的值
            setIsFavorite(body.isFavorite)
        }
    }
    const handleFavorite = async() => {
        
        const isLogin = getToken()
        if (!isLogin) {
            // 未登录
            return Dialog.show({
                title: '提示',
                content: '登录后才能收藏房源，是否去登录?',
                closeOnAction: true,
                onAction: (action) => {
                    if (action.key === 'cancel') {
                        return
                    }
                    navigate('/login')
                },
                actions: [
                    [{
                        key: 'cancel',
                        text: '取消',
                    },
                    {
                        key: 'success',
                        text: '去登陆',
                        bold: true,
                        success: true,
                    }]
                ]
            })
        }
        const id = location.pathname.split('/')[2]
        if(isFavorite){
            const res = await delFavoritesAPI(id)
            // console.log(res);
            setIsFavorite(false)
            if (res.status === 200) {
                // 提示用户取消收藏
                Toast.show({icon: 'success',content: '已取消收藏',})
              } else {
                // token 超时
                Toast.show({icon: 'fail',content: '取消收藏失败',})
              }
        }else {
            const res = await addFavoritesAPI(id)
            setIsFavorite(true)
            if (res.status === 200) {
                // 提示用户取消收藏
                Toast.show({icon: 'success',content: '收藏成功',})
              } else {
                // token 超时
                Toast.show({icon: 'fail',content: '收藏失败',})
              }
        }
    }
    useEffect(() => {
        const id = location.pathname.split('/')[2]
        getHouseDetail(id)
        checkFavorite(id)
    }, [])
    // 渲染地图
    function renderMap(community, coord) {
        const { latitude, longitude } = coord

        const map = new BMap.Map('map')
        const point = new BMap.Point(longitude, latitude)
        map.centerAndZoom(point, 17)

        const label = new BMap.Label('', {
            position: point,
            offset: new BMap.Size(0, -36)
        })

        label.setStyle(labelStyle)
        label.setContent(`
            <span>${community}</span>
            <div class="mapArrow"></div>
    `)
        map.addOverlay(label)
    }
    const onPhone = () => {
        setVisible(true)
    }
    return (
        <div className='house__detail'>
            <div className='house__detail__header'>
                <NavBar onBack={() => navigate(-1)}>{houseDetail.community}</NavBar>
                <Swiper
                    loop
                    autoplay
                >
                    {houseDetail.houseImg?.map((item, index) => (
                        <Swiper.Item key={index}>
                            <div
                                className='house__img'
                            >
                                <img src={baseURL + item} />
                            </div>
                        </Swiper.Item>
                    ))}
                </Swiper>
                <ul className='house__detail__content'>
                    <li className='title'>
                        <p>{houseDetail.title}</p>
                        <div>
                            {houseDetail.tags?.map(item => (
                                <Tag color='#2db7f5' key={item}>{item}</Tag>
                            )
                            )}
                        </div>
                    </li>
                    <li className='price'>
                        <div>{houseDetail.price}<i>/月</i><span>租金</span></div>
                        <div>{houseDetail.roomType}<span>房型</span></div>
                        <div>{houseDetail.size}平米<span>面积</span></div>
                    </li>
                    <li className='other'>
                        <div>
                            <div>
                                <span>装修 :</span>精装
                            </div>
                            <div>
                                <span>楼层 :</span>{houseDetail.floor}
                            </div>
                        </div>
                        <div>
                            <div>
                                <span>朝向 :</span>{houseDetail.oriented}
                            </div>
                            <div>
                                <span>类型 :</span>普通住宅
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
            <div className='blank'></div>
            <div className='house__detail__map'>
                <h3 className='title'><span>小区：</span>{houseDetail.community}</h3>
                <div className='map__container' id='map'>
                </div>
            </div>
            <div className='blank'></div>
            <div className='house__detail__desc'>
                <p>
                    {houseDetail.description ? houseDetail.description : '暂无描述'}
                </p>
            </div>
            <div className='blank'></div>
            <div className='house__detail__supporting'>
                <h3>房屋配置</h3>
                {houseDetail.length > 0 
                ? <HousePackage list={houseDetail.supporting} />
                : <p>暂无配置</p>
                }
                
            </div>
            <div className='house__detail__footer'>
                <div onClick={handleFavorite}>
                    <img className='star' src={ baseURL + (isFavorite ? '/img/star.png' :'/img/unstar.png')} />
                    <span>收藏</span>
                </div>
                <div>
                    在线咨询
                </div>
                <div className='phone' onClick={onPhone}>
                    电话预约
                </div>

            </div>
            <Modal
                visible={visible}
                content='tel:400-618-4000'
                closeOnAction
                onClose={() => {
                    setVisible(false)
                }}
                actions={[
                    {
                        key: 'confirm',
                        text: '我知道了',
                    },
                ]}
            />
        </div>
    )
}
